﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;

namespace Web.Invoice
{
    public partial class Invoices : System.Web.UI.Page
    {
        static USER user;
        static List<INVOICE_DETAIL> invoiceDetails;
        static long? assignedtoID = null;
        static ROLE r;
        static List<long?> ListOrgID;
        static List<long?> ListConID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            assignedtoID = null;
            user = (USER)Session["User"];
            if (user != null)
            {
                DateTime dt = DateTime.Now;
                DateTime dt2 = dt.AddMonths(-3);
                dpDateCreatedFrom.SelectedDate = new DateTime(dt2.Year, dt2.Month, 1);
                dpDateCreatedTo.SelectedDate = DateTime.Now;
                r = RoleService.GetRoleByID((long)user.ROLE_ID);
                if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                {
                    assignedtoID = user.ID;
                    divAssignTo.Visible = false;
                }
                ListOrgID = new List<long?>();
                ListConID = new List<long?>();
                invoiceDetails = getDataSource(dpDateCreatedFrom.SelectedDate, dpDateCreatedTo.SelectedDate.Value.AddHours(24), null, ListConID, ListOrgID, assignedtoID);
                RadGrid1.DataSource = invoiceDetails;
                RadGrid1.DataBind();
                /////////////////////////////////////
                ddlStatus.DataSource = InvoiceService.GetAllInvoiceStatus();
                ddlStatus.DataBind();
                ddlStatus.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));

                LoadAllUser(ddlAssignedTo);
                if (ddlAssignedTo.Items.Count > 0)
                    ddlAssignedTo.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
                ViewState["CurrentStatusFilter"] = "-1";
                ViewState["CurrentAssignToFilter"] = "-1";

            }
        }
        private List<INVOICE_DETAIL> getDataSource(DateTime? dateFrom, DateTime? dateTo, long? status_ID, List<long?> ListConID, List<long?> ListOrgID, long? assignUser_ID)
        {
            List<INVOICE_DETAIL> dt = InvoiceService.GetInvoiceByCondition(dateFrom, dateTo, status_ID, ListConID, ListOrgID, assignUser_ID);
            if (dt == null)
            {
                dt = new List<INVOICE_DETAIL>();
            }
            return dt;
        }
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = invoiceDetails;
        }

        protected void btnSearch_ServerClick(object sender, EventArgs e)
        {
            long? qs = null;
            if (ddlStatus.SelectedValue != "-1")
                qs = Convert.ToInt64(ddlStatus.SelectedValue);
            if (divAssignTo.Visible)
            {
                long? at = Convert.ToInt64(ddlAssignedTo.SelectedValue);
                assignedtoID = at == -1 ? null : at;
            }

            ListOrgID = new List<long?>();
            ListConID = new List<long?>();

            string str1 = hdntxtConID.Value;
            string[] arr1 = str1.Split(';');
            foreach (string str in arr1)
            {
                if (str != "")
                {
                    ListConID.Add(Convert.ToInt64(str));
                }
            }
            str1 = hdntxtOrgID.Value;
            arr1 = str1.Split(';');
            foreach (string str in arr1)
            {
                if (str != "")
                {
                    ListOrgID.Add(Convert.ToInt64(str));
                }
            }

            invoiceDetails = getDataSource(dpDateCreatedFrom.SelectedDate, dpDateCreatedTo.SelectedDate.Value.AddHours(24), qs, ListConID, ListOrgID, assignedtoID);
            RadGrid1.DataSource = invoiceDetails;
            RadGrid1.DataBind();
        }
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            GridDataItem dataItem = e.Item as GridDataItem;
            switch (e.CommandName)
            {
                case "Edit":
                    {
                        Response.Redirect("EditInvoice.aspx?id=" + dataItem.GetDataKeyValue("InvoiceID").ToString());
                        break;
                    }
                case "View":
                    {
                        Response.Redirect("ViewInvoice.aspx?id=" + dataItem.GetDataKeyValue("InvoiceID").ToString());
                        break;
                    }
                default:
                    break;
            }
        }

        private void LoadAllUser(RadComboBox ddlAssignedTo)
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
        }

        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem oGridPagerItem = (GridPagerItem)e.Item;
                RadComboBox oRadComboBox = (RadComboBox)oGridPagerItem.FindControl("PageSizeComboBox");
                oRadComboBox.Width = Unit.Pixel(50);
            }
            if (e.Item is GridDataItem)
            {
                GridDataItem item = (GridDataItem)e.Item;
                LinkButton lbtnEdit = (LinkButton)item.FindControl("lbtnEdit");
                LinkButton lbtnView = (LinkButton)item.FindControl("lbtnView");
                lbtnView.Visible = false;
                long id = Convert.ToInt64(item.GetDataKeyValue("InvoiceID"));
                foreach (INVOICE_DETAIL inv in invoiceDetails)
                {
                    if ((inv.InvoiceID == id) && (inv.SAVED_STATE == true))
                    {
                        lbtnEdit.Visible = false;
                        lbtnView.Visible = true;
                        break;
                    }
                }
            }
        }

        protected void btnAddInvoice_ServerClick(object sender, EventArgs e)
        {
            Response.Redirect("AddNewInvoice.aspx");
        }

        protected void RadGrid1_PreRender(object sender, EventArgs e)
        {

            if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
            {
                RadGrid1.MasterTableView.GetColumn("ASSIGN_TO").Visible = false;
                RadGrid1.MasterTableView.GetColumn("INVOICE_NUMBER").ItemStyle.Width = Unit.Percentage(15);
                RadGrid1.MasterTableView.GetColumn("INVOICE_NUMBER").HeaderStyle.Width = Unit.Percentage(15);
                RadGrid1.MasterTableView.GetColumn("CONTACT_NAME").ItemStyle.Width = Unit.Percentage(20);
                RadGrid1.MasterTableView.GetColumn("CONTACT_NAME").HeaderStyle.Width = Unit.Percentage(20);
            }
            foreach (GridGroupHeaderItem groupHeader in RadGrid1.MasterTableView.GetItems(GridItemType.GroupHeader))
            {
                GridDataItem item = groupHeader.GetChildItems()[0] as GridDataItem;
                object key = item.GetDataKeyValue("OrgID");
                string strtxt = groupHeader.DataCell.Text;

                Label lbl = new Label();
                lbl.ID = "lblGroupHeader";
                lbl.Text = (key == null ? "NULL" : strtxt.Replace("ORGANIZATION_NAME: ", ""));
                lbl.ForeColor = System.Drawing.Color.Blue;
                groupHeader.DataCell.Controls.Clear();
                groupHeader.DataCell.Controls.Add(lbl);
            }
        }

        protected void btnCloseRadWin_ServerClick(object sender, EventArgs e)
        {

        }
    }
}